require('../css/mine-edit.less')
document.ready(function () {

    // 判断用户是否登录，若没登陆，跳转到登录页
    window.utils.checkUserLogin();

    let backBtn = document.querySelector("#backBtn"); //返回
    let js_input = document.querySelector("#js_input"); //昵称

    let sexPicker = document.querySelector("#sexPicker"); //性别
    let sexText = document.querySelector("#sexText"); //选择性别

    let birthdayPicker = document.querySelector("#birthdayPicker"); //生日
    let birthdayText = document.querySelector("#birthdayText"); //选择生日

    let provincePicker = document.querySelector("#provincePicker"); //所在省份
    let provinceText = document.querySelector("#provinceText"); //选择省份

    let cityPicker = document.querySelector("#cityPicker"); //所在城市
    let cityText = document.querySelector("#cityText"); //选择城市

    let sign = document.querySelector("#sign"); //选择城市

    let saveBtn = document.querySelector("#saveBtn"); //保存信息

    //获取本地数据  (如果本地有数据就渲染否则就不渲染)
    let user = JSON.parse(localStorage.getItem('user'))
    console.log(user);
    js_input.value = user.nickname
    if (user.gender) {
        sexText.textContent = user.gender
    }
    if (user.birthday) {
        birthdayText.textContent = user.birthday.substr(0,10)
    }
    if (user.address) {
        provinceText.textContent = user.address.split(',')[0]
        cityText.textContent = user.address.split(',')[1]
    }
    // sign.value=user.sign

    //返回上一页
    backBtn.addEventListener('click', function () {
        history.back();
        location.href = './mine.html'
    })

    //选择性别
    sexPicker.addEventListener('click', function () {
        weui.picker([{
            label: '男',
            value: 0
        }, {
            label: '女',
            value: 0
        }], {
            onConfirm: function (result) {
                sexText.textContent = result[0].label
            },
            title: '单列选择器'
        });
    })

    //选择生日
    birthdayPicker.addEventListener('click', function () {
        weui.datePicker({
            start: 1990,
            end: new Date().getFullYear(),

            onConfirm: function (result) {
                // console.log(result);
                let y = result[0].value;
                let m = result[1].value;
                let d = result[2].value;
                //处理年月日结构
                let birthdayval = [y, m, d].map(function (v) {
                    return window.utils.addZero(v);
                }).join('-')
                // console.log(birthdayval);
                birthdayText.textContent = birthdayval
            },
            title: '多列选择器'
        });

    })

    //发ajax获取省份数据
    $http.get(`/address/province?userId=${user.userId}`, function (pData) {
        if (pData.status === 0) {
            let arr = pData.data
            let province = arr.map(function (item) {
                return {
                    label: item.name,
                    value: item.addressId
                }
            })
            //点击选择所在省份
            let prevHandleCityPick; //这个变量用来保存城市上一次的执行函数

            provincePicker.addEventListener('click', function () {
                weui.picker(province, {
                    onConfirm: function (result) {
                        provinceText.textContent = result[0].label
                        console.log('pData.addressId', result[0].value);

                        //发ajax用 省份ID 获取城市数据
                        $http.get(`/address/city/${result[0].value}`, function (cData) {
                            if (cData.status === 0) {
                                let arr = cData.data
                                let city = arr.map(function (item) {
                                    return {
                                        label: item.name,
                                        value: item.addressId
                                    }
                                })

                                function handleCityPick() {
                                    weui.picker(city, {
                                        onConfirm: function (result) {

                                            console.log("onConfirm");
                                            console.log(result);
                                            cityText.textContent = result[0].label
                                        },
                                        title: '单列选择器'
                                    });

                                }

                                //解绑 所选城市（上一次）绑定事件
                                cityPicker.removeEventListener('click', prevHandleCityPick);
                                cityText.textContent = '未选择'
                                //每次选择之前保存之前的城市
                                prevHandleCityPick = handleCityPick;

                                //绑定事件---配置所选城市
                                cityPicker.addEventListener('click', handleCityPick);


                            }
                        })

                    },
                    title: '单列选择器'
                });
            })



        }
    })



    //个性签名
    sign.addEventListener('input', function (e) {
        signNum.textContent = this.value.length
        // console.log(sign.value);
        if (this.value.length >= "200") {
            // let str = sign.value
            // let str1 = str.substr(1, 10);
            sign.setAttribute("disabled", 'true')

        }
    })



    //保存信息
    saveBtn.addEventListener('click', function () {
        let nickNameVal = js_input.value;
        if (nickNameVal === '') {
            hint.textContent = '昵称不能为空'
            return
        } else if (nickNameVal.length > 7) {
            hint.textContent = '昵称长度不能超过7个字符'
            return
        }
        let genderVal = sexText.textContent === '未选择' ? '' : sexText.textContent //性别
        let birthdayVal = birthdayText.textContent === '未选择' ? '' : birthdayText.textContent //生日
        let provinceVal = provinceText.textContent === '未选择' ? '' : provinceText.textContent //省份
        let cityVal = cityText.textContent === '未选择' ? '' : cityText.textContent //城市
        let signVal = sign.value; // 个人签名

        // let bir = new Date(birthdayText.textContent).getTime(); //转时间戳
        let birth = new Date(birthdayText.textContent).toISOString();//转格林威治
        console.log('格林威治',birth);
        

        $http.post('/users/userEdit', {
            userId: user.userId,
            nickname: js_input.value,
            gender: sexText.textContent,
            birthday: new Date(birthdayText.textContent).toISOString(),//转格林威治
            address: [provinceText.textContent, cityText.textContent],
            sign: sign.value,
        }, function (res) {
            if (res.status === 0) {
                let obj = {
                    userId: user.userId,
                    account: user.account,
                    password: user.password,
                    nickname: js_input.value,
                    gender: sexText.textContent,
                    birthday: new Date(birthdayText.textContent).toISOString(), //转格林威治
                    imgurl: user.imgurl,
                    address: `${provinceText.textContent},${cityText.textContent}`,
                    sign: sign.value,
                    describe: user.describe,
                    token: user.token
                }
                console.log(obj);
                localStorage.setItem('user', JSON.stringify(obj))
                window.utils.toast('tick', '保存成功');
                // location.href='./mine.html'
            }
        })
    })


})